package com.pt25.study.example.interfaces.facade.test;


import com.pt25.base.dep.kafka.KafkaProducerService;
import com.pt25.base.model.common.constants.KafkaConstant;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.Executor;

@Slf4j
@Tag(name = "kafka test api")
@RefreshScope
@RestController
@RequestMapping("/test-api/example")
public class KafkaTestController {
    private final static String TEST_KAFKA_PRODUCE = "/test-kafka-producer";
    @Resource
    private KafkaProducerService kafkaProducerService;

    @Resource(name = "kafkaExecutor")
    private Executor kafkaExecutor;

    @Operation(summary = "测试kafka数据发送")
    @GetMapping(TEST_KAFKA_PRODUCE)
    public String testKafkaProduce() {
        for (int i = 0; i < 30; i++) {
            kafkaProducerService.getKafkaTemplate(KafkaConstant.PRODUCER1).send("test_topic1", "hello kafka!");
        }
        return "OK";
    }

    /**
     * kafka数据消费
     * 采用线程池异步消费数据，提高消费速度
     */
    @KafkaListener(topics = "test_topic1", groupId = "test_group_id1", containerFactory = KafkaConstant.CONSUMER1)
    public void listenCluster1(String message) {
        kafkaExecutor.execute(() -> {
            log.info("thread:{};message:{}", Thread.currentThread().getId(), message);
        });
    }

    /**
     * 批量消费
     */
    @KafkaListener(topics = "test_topic1", groupId = "test_group_id2", containerFactory = KafkaConstant.CONSUMER1)
    public void batchConsume(List<String> datas) {
        log.info("datas size:{}", datas.size());
    }
}
